package com.walker.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * 描述:公共日期工具类
 */
public class DateUtils {

	public static String DATE_FORMAT = "yyyy-MM-dd";
	
	public static String DATE_FORMAT_X = "yyyy/MM/dd";

	public static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

	public static String DATE_FORMAT_CHINESE = "yyyy年M月d日";
	
	public static String DATE_FORMAT_month = "yyyy-MM";
	
	public static String DATE_FORMAT_hour = "HH:mm";
	
	public static String DATE_FORMAT_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'";

	/**
	 * 获取当前日期
	 * @return
	 */
	public static String getCurrentDate() {
		String datestr = null;
		SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
		datestr = df.format(new Date());
		return datestr;
	}

	/**
	 * 获取当前日期时间
	 * @return
	 */
	public static String getCurrentDateTime() {
		String datestr = null;
		SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT);
		datestr = df.format(new Date());
		return datestr;
	}

	/**
	 * 获取当前日期时间
	 * @return
	 */
	public static String getCurrentDateTime(String Dateformat) {
		String datestr = null;
		SimpleDateFormat df = new SimpleDateFormat(Dateformat);
		datestr = df.format(new Date());
		return datestr;
	}

	public static String dateToDateTime(Date date) {
		String datestr = null;
		SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT);
		datestr = df.format(date);
		return datestr;
	}

	/**
	 * 将字符串日期转换为日期格式
	 * @param datestr
	 * @return
	 */
	public static Date stringToDate(String datestr) {

		if (datestr == null || datestr.equals("")) {
			return null;
		}
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
		try {
			date = df.parse(datestr);
		} catch (ParseException e) {
			date = DateUtils.stringToDate(datestr, "yyyyMMdd");
		}
		return date;
	}

	/**
	 * 将字符串日期转换为日期格式 自定義格式
	 * @param datestr
	 * @return
	 * 
	 */
	public static Date stringToDate(String datestr, String dateformat) {
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat(dateformat);
		try {
			date = df.parse(datestr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 将日期格式日期转换为字符串格式
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date) {
		String datestr = null;
		SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
		datestr = df.format(date);
		return datestr;
	}

	/**
	 * 将日期格式日期转换为字符串格式 自定義格式
	 * @param date
	 * @param dateformat
	 * @return
	 */
	public static String dateToString(Date date, String dateformat) {
		String datestr = null;
		SimpleDateFormat df = new SimpleDateFormat(dateformat);
		df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		datestr = df.format(date);
		return datestr;
	}

	/**
	 * 获取日期的DAY值
	 * @param date 输入日期
	 * @return
	 */
	public static int getDayOfDate(Date date) {
		int d = 0;
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);
		d = cd.get(Calendar.DAY_OF_MONTH);
		return d;
	}

	/**
	 * 获取日期的MONTH值
	 * @param date 输入日期
	 * @return
	 */
	public static int getMonthOfDate(Date date) {
		int m = 0;
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);
		m = cd.get(Calendar.MONTH) + 1;
		return m;
	}

	/**
	 * 获取日期的YEAR值
	 * @param date 输入日期
	 * @return
	 */
	public static int getYearOfDate(Date date) {
		int y = 0;
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);
		y = cd.get(Calendar.YEAR);
		return y;
	}

	/**
	 * 获取星期几
	 * @param date 输入日期
	 * @return
	 */
	public static int getWeekOfDate(Date date) {
		int wd = 0;
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);
		wd = cd.get(Calendar.DAY_OF_WEEK) - 1;
		return wd;
	}

	/**
	 * 获取输入日期的当月第一天
	 * @param date 输入日期
	 * @return
	 */
	public static Date getFirstDayOfMonth(Date date) {
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);
		cd.set(Calendar.DAY_OF_MONTH, 1);
		return cd.getTime();
	}

	/**
	 * 获得输入日期的当月最后一天
	 * @param date
	 */
	public static Date getLastDayOfMonth(Date date) {
		return DateUtils.addDay(DateUtils.getFirstDayOfMonth(DateUtils.addMonth(date, 1)), -1);
	}

	/**
	 * 判断是否是闰年
	 * @param date 输入日期
	 * @return 是true 否false
	 */
	public static boolean isLeapYEAR(Date date) {

		Calendar cd = Calendar.getInstance();
		cd.setTime(date);
		int year = cd.get(Calendar.YEAR);

		if (year % 4 == 0 && year % 100 != 0 | year % 400 == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据整型数表示的年月日，生成日期类型格式
	 * @param year 年
	 * @param month 月
	 * @param day 日
	 * @return
	 */
	public static Date getDateByYMD(int year, int month, int day) {
		Calendar cd = Calendar.getInstance();
		cd.set(year, month - 1, day);
		return cd.getTime();
	}

	/**
	 * 获取年周期对应日
	 * @param date 输入日期
	 * @param iyear 年数 負數表示之前
	 * @return
	 */
	public static Date getYearCycleOfDate(Date date, int iyear) {
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);

		cd.add(Calendar.YEAR, iyear);

		return cd.getTime();
	}

	/**
	 * 获取月周期对应日
	 * @param date 输入日期
	 * @param i
	 * @return
	 */
	public static Date getMonthCycleOfDate(Date date, int i) {
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);

		cd.add(Calendar.MONTH, i);

		return cd.getTime();
	}

	/**
	 * 计算 fromDate 到 toDate 相差多少年
	 * @param fromDate
	 * @param toDate
	 * @return 年数
	 */
	public static int getYearByMinusDate(Date fromDate, Date toDate) {
		Calendar df = Calendar.getInstance();
		df.setTime(fromDate);

		Calendar dt = Calendar.getInstance();
		dt.setTime(toDate);

		return dt.get(Calendar.YEAR) - df.get(Calendar.YEAR);
	}

	/**
	 * 计算 fromDate 到 toDate 相差多少个月
	 * @param fromDate
	 * @param toDate
	 * @return 月数
	 */
	public static int getMonthByMinusDate(Date fromDate, Date toDate) {
		Calendar df = Calendar.getInstance();
		df.setTime(fromDate);

		Calendar dt = Calendar.getInstance();
		dt.setTime(toDate);

		return dt.get(Calendar.YEAR) * 12 + dt.get(Calendar.MONTH)
				- (df.get(Calendar.YEAR) * 12 + df.get(Calendar.MONTH));
	}

	/**
	 * 计算 fromDate 到 toDate 相差多少天
	 * @param fromDate
	 * @param toDate
	 * @return 天数
	 */
	public static long getDayByMinusDate(Object fromDate, Object toDate) {

		Date f = DateUtils.chgObject(fromDate);

		Date t = DateUtils.chgObject(toDate);

		long fd = f.getTime();
		long td = t.getTime();

		return (td - fd) / (24L * 60L * 60L * 1000L);
	}

	/**
	 * 计算年龄
	 * @param birthday 生日日期
	 * @param calcDate 要计算的日期点
	 * @return
	 */
	public static int calcAge(Date birthday, Date calcDate) {

		int cYear = DateUtils.getYearOfDate(calcDate);
		int cMonth = DateUtils.getMonthOfDate(calcDate);
		int cDay = DateUtils.getDayOfDate(calcDate);
		int bYear = DateUtils.getYearOfDate(birthday);
		int bMonth = DateUtils.getMonthOfDate(birthday);
		int bDay = DateUtils.getDayOfDate(birthday);

		if (cMonth > bMonth || (cMonth == bMonth && cDay > bDay)) {
			return cYear - bYear;
		} else {
			return cYear - 1 - bYear;
		}
	}

	/**
	 * 从身份证中获取出生日期
	 * @param idno 身份证号码
	 * @return
	 */
	public static String getBirthDayFromIDCard(String idno) {
		Calendar cd = Calendar.getInstance();
		if (idno.length() == 15) {
			cd.set(Calendar.YEAR, Integer.valueOf("19" + idno.substring(6, 8)).intValue());
			cd.set(Calendar.MONTH, Integer.valueOf(idno.substring(8, 10)).intValue() - 1);
			cd.set(Calendar.DAY_OF_MONTH, Integer.valueOf(idno.substring(10, 12)).intValue());
		} else if (idno.length() == 18) {
			cd.set(Calendar.YEAR, Integer.valueOf(idno.substring(6, 10)).intValue());
			cd.set(Calendar.MONTH, Integer.valueOf(idno.substring(10, 12)).intValue() - 1);
			cd.set(Calendar.DAY_OF_MONTH, Integer.valueOf(idno.substring(12, 14)).intValue());
		}
		return DateUtils.dateToString(cd.getTime());
	}

	/**
	 * 在输入日期上增加（+）或减去（-）天数
	 * @param date 输入日期
	 * @param imonth 要增加或减少的天数
	 */
	public static Date addDay(Date date, int iday) {
		Calendar cd = Calendar.getInstance();

		cd.setTime(date);

		cd.add(Calendar.DAY_OF_MONTH, iday);

		return cd.getTime();
	}

	/**
	 * 在输入日期上增加（+）或减去（-）月份
	 * @param date 输入日期
	 * @param imonth 要增加或减少的月分数
	 */
	public static Date addMonth(Date date, int imonth) {
		Calendar cd = Calendar.getInstance();

		cd.setTime(date);

		cd.add(Calendar.MONTH, imonth);

		return cd.getTime();
	}

	/**
	 * 在输入日期上增加（+）或减去（-）年份
	 * @param date 输入日期
	 * @param imonth 要增加或减少的年数
	 */
	public static Date addYear(Date date, int iyear) {
		Calendar cd = Calendar.getInstance();

		cd.setTime(date);

		cd.add(Calendar.YEAR, iyear);

		return cd.getTime();
	}

	/**
	 * 將OBJECT類型轉換為Date
	 * @param date
	 * @return
	 */
	public static Date chgObject(Object date) {
		if (date != null && date instanceof Date) {
			return (Date) date;
		}

		if (date != null && date instanceof String) {
			return DateUtils.stringToDate((String) date);
		}
		return null;
	}

	public static long getAgeByBirthday(String date) {

		Date birthday = stringToDate(date, "yyyy-MM-dd");
		long sec = new Date().getTime() - birthday.getTime();

		long age = sec / (1000 * 60 * 60 * 24) / 365;

		return age;
	}

	/**
	 * 获取过去的分钟
	 * @param date
	 * @return
	 */
	public static long pastMinutes(Date date) {
		long t = new Date().getTime() - date.getTime();
		return t / (60 * 1000);
	}

	public static List<String> getTwoDaysDay(String dateStart, String dateEnd, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat returnsdf = new SimpleDateFormat(format);
		List<String> dateList = new ArrayList<String>();
		try {
			Date dateOne = sdf.parse(dateStart);
			Date dateTwo = sdf.parse(dateEnd);

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(dateTwo);

			dateList.add(returnsdf.format(sdf.parse(dateEnd)));
			while (calendar.getTime().after(dateOne)) { // 倒序时间,顺序after改before其他相应的改动。
				calendar.add(Calendar.DAY_OF_MONTH, -1);
				dateList.add(returnsdf.format(calendar.getTime()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dateList;
	}
	
	public static List<String> getTwoDaysDayZDY(String dateStart, String dateEnd, String format, String sdfFormat, Integer type) {
		SimpleDateFormat sdf = new SimpleDateFormat(sdfFormat);
		SimpleDateFormat returnsdf = new SimpleDateFormat(format);
		List<String> dateList = new ArrayList<String>();
		try {
			Date dateOne = sdf.parse(dateStart);
			Date dateTwo = sdf.parse(dateEnd);

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(dateTwo);

			dateList.add(returnsdf.format(sdf.parse(dateEnd)));
			while (calendar.getTime().after(dateOne)) { // 倒序时间,顺序after改before其他相应的改动。
				calendar.add(type, -1);
				dateList.add(returnsdf.format(calendar.getTime()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dateList;
	}
	
	/**
	 * 日期格式按照年月日时分秒毫秒格式来校验
	 * @param date
	 * @return
	 */
	public static boolean isValidDate(String date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		try{
			sdf.setLenient(false);//严格按照给定的格式来校验
			sdf.parse(StringUtils.trim(date));
			return true;
		}catch(Exception e){
			return false;
		}
	}
	
	public static boolean isValidDate(String date,String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try{
			sdf.setLenient(false);//严格按照给定的格式来校验
			sdf.parse(StringUtils.trim(date));
			return true;
		}catch(Exception e){
			return false;
		}
	}
	
    /**
	 * 获取昨天时间
	 */
	public static Date getYesterdayTime(){
		Calendar calendar=Calendar.getInstance();
		calendar.add(Calendar.DATE,-1); //昨天数据
		return calendar.getTime();
	}
	
    /**
	 * 获取今天时间
	 */
	public static Date getCurrentTime(){
		Calendar calendar=Calendar.getInstance();
		return calendar.getTime();
	}
    /**
	 * 获取前天时间
	 */
	public static Date getBeforeYesterdayTime(){
		Calendar calendar=Calendar.getInstance();
		calendar.add(Calendar.DATE,-2); //昨天数据
		return calendar.getTime();
	}

    /**
	 * 获取上个小时时间, 小时
	 */
	public static Date getBeforeHourTime(){

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, -1);
		return cal.getTime();
	}
	
	/**
	 * @param sDate
	 * @return
	 */
	public static boolean isValidDateAll(Object sDate) {
		String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
		String datePattern2 = "\\d{4}\\d{2}\\d{2}";
		String datePattern3 = "\\d{4}/\\d{2}/\\d{2}";
		
		if ((sDate != null)) {
			Pattern pattern1 = Pattern.compile(datePattern1);
			Matcher match1 = pattern1.matcher(sDate.toString());
		
			Pattern pattern2 = Pattern.compile(datePattern2);
			Matcher match2 = pattern2.matcher(sDate.toString());
		
			Pattern pattern3 = Pattern.compile(datePattern3);
			Matcher match3 = pattern3.matcher(sDate.toString());
		
			if (match1.matches() || match2.matches()||match3.matches()) {
				return true;
			}else {
				return false;
			}
		}
		return false;
	}
	
	/**
	* 功能描述：返回小时
	* @param date 日期
	* @return 返回小时
	*/
	public static int getHour() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	/**
	* 功能描述：返回分
	* @param date 日期
	* @return 返回分钟
	*/
	public static int getMinute() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.MINUTE);
	}
	
	/**
	 * 延迟N分钟
	 */
	public static int getDelayMinute(int time){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, time);
		return calendar.get(Calendar.MINUTE);
	}
	
	/**
	* 功能描述：延迟N分钟返回小时
	* @param date 日期
	* @return 返回小时
	*/
	public static int getDelayHour(int time) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, time);
		return calendar.get(Calendar.HOUR_OF_DAY);
	}
	
	public static String getDelayHour(int delay,String format) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, -delay);
		return new SimpleDateFormat(format).format(calendar.getTime());
	}
	
	public static String getDelayDay(int delay,String format){
		Calendar calendar=Calendar.getInstance();
		calendar.add(Calendar.DATE,-delay); 
		return new SimpleDateFormat(format).format(calendar.getTime());
	}
	
	
	public static String getFormatDay(String dateStr, String dateFormat) {
		String day = "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			day = new SimpleDateFormat(dateFormat).format(df.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return day;
	}
	
	public static String timestamp2Date(String strNum ) {
	    SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
	    if (strNum.length() == 13) {
	        String date = sdf.format(new Date(Long.parseLong(strNum)));
	        return date;
	    } else {
	        String date = sdf.format(new Date(Integer.parseInt(strNum) * 1000L));
	        return date;
	    }
	}
	
	public static String longToStr(long time,String dateformat){
		Date date=new Timestamp(time);
		return dateToString(date, dateformat);
	}

	public static String replaceDate(String sql,String date){
		String regex = "(\\{(.*?)})";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(sql);
		while (matcher.find()) {
			String format=matcher.group(1);
			format=format.substring(1,format.length()-1);
			sql=sql.replace("$"+matcher.group(1), DateUtils.dateToString(DateUtils.stringToDate(date, format),format));
		}
		return sql;
	}
	
	public static String getDelayHour(int delay, String format,Date date) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.HOUR, -delay);
		return new SimpleDateFormat(format).format(calendar.getTime());
	}
	
	public static String getDelayDay(int delay,String format,Date date) throws ParseException{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE,-delay); 
		return new SimpleDateFormat(format).format(calendar.getTime());
	}
	
	public static String getDelay(int delay, String format,Date date) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.HOUR, -delay);
		calendar.add(Calendar.MINUTE, -delay);
		calendar.add(Calendar.SECOND, -delay);
		return new SimpleDateFormat(format).format(calendar.getTime());
	}
	
	/**
	 * 时间戳转换成字符串
	 */
		public static String getDateToString(Object time) {
				Date d = new Date(Long.parseLong(String.valueOf(time)));
				SimpleDateFormat  sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				return sf.format(d);
		}
}